:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Switching the JDK environment.
:: 
:: Author: ZHANGQ
:: Create Time: 2020-06-26
:: 
:: Arguments:
::   %1 - The name of the JDK release. (see 'jdk-data.ini' file)
::   %2 - The name of the language. ('ZH' or 'EN')
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

@ECHO OFF

:: validate pass arguments
SET jdk_release_arg=%1
SET lang_arg=%2

IF NOT DEFINED jdk_release_arg (
    ECHO Please enter a JDK release.
    GOTO QUIT-SCRIPT
)

IF NOT DEFINED lang_arg (
    ECHO Please enter environment language.
    GOTO QUIT-SCRIPT
)

:: query from jdk-data.ini, validate jdk release argument
SET data_file=%~dp0\jdk-data-win.ini
FOR /F "tokens=*" %%i IN (%data_file%) DO (
    ECHO Processing '%%i'

    :: split string in line
    FOR /F "delims== tokens=1*" %%a IN ("%%i") DO (
        IF /I %%a==%jdk_release_arg% (
            ECHO Found '%%a': '%%b'
            CALL :NEXT_VALIDATE_JDK %%a "%%b"
            GOTO NEXT_VALIDATE_LANG
        )
    )
)

ECHO The JDK release Named '%jdk_release_arg%' was not found.
GOTO QUIT-SCRIPT

:NEXT_VALIDATE_JDK

SET jdk_name=%1
SET jdk_path=%2

GOTO :EOF

:NEXT_VALIDATE_LANG

SET lang_arg=%lang_arg:z=Z%
SET lang_arg=%lang_arg:h=H%
SET lang_arg=%lang_arg:e=E%
SET lang_arg=%lang_arg:n=N%

IF NOT "%lang_arg%"=="ZH" (
    IF NOT "%lang_arg%"=="EN" (
        ECHO Please enter the correct environment language.
        GOTO QUIT-SCRIPT
    ) ELSE (
        SET country=US
    )
) ELSE (
    SET country=CN
)

:: recover old environment and backup current environment and set new environment
:SET-ENVIRONMENT

CALL inactivate-jdk.bat

:: backup current environment
SET PATH_BEFORE_JDK=%PATH%
SET PROMPT_BEFORE_JDK=%PROMPT%
ECHO Backing up the current environment 'PATH' and 'PROMPT'.

:: set new environment variables
SET JAVA_HOME=%jdk_path:~1,-1%
ECHO Setting 'JAVA_HOME' environment validate.

SET JAVA_TOOL_OPTIONS=-Duser.country=%country% -Duser.language=%lang_arg% -Dfile.encoding=utf-8
ECHO Setting 'JAVA_TOOL_OPTIONS' environment validate.

SET PATH=%JAVA_HOME%\bin;%PATH%
ECHO Setting 'PATH' environment validate.

SET PROMPT=(%jdk_name% UTF8 %lang_arg%) $P$G
ECHO Setting the command line prompt.

:: set codepage: utf8
"%SystemRoot%\System32\chcp.com" 65001 > nul
ECHO Set up the UFT8 environment.

:: quit script
:QUIT-SCRIPT

SET jdk_release_arg=
SET lang_arg=
SET data_file=
SET country=
SET jdk_release_line=
SET jdk_name=
SET jdk_path=

EXIT /B
